package com.zecan.blog.utils;

import com.zecan.blog.common.status.UserStatus;
import com.zecan.blog.controller.exception.UserException;
import com.zecan.blog.rabbitmq.event.SendEmailEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class MailSendUtil {

    @Resource
    private JavaMailSender javaMailSender;


    @Value(value = "${spring.mail.username}")
    private String username;

    public void sendMail(SendEmailEvent sendEmailEvent) {
        MimeMessage message;
        MimeMessageHelper helper;
        if(sendEmailEvent == null)  {
            return;
        }
        String toUser = sendEmailEvent.getToUser();
        String content = sendEmailEvent.getContent();
        String subject = sendEmailEvent.getSubject();
        Boolean isRegistry = sendEmailEvent.getIsRegistry();
        try {
            message = javaMailSender.createMimeMessage(); // 创建流
            helper = new MimeMessageHelper(message,true); // 进行绑定
            helper.setFrom(username);
            helper.setTo(toUser);
//            <img src='cid:welcomeToBlog'>"
            if(isRegistry) {
                helper.setText("<html><body>" +
                        toUser + "您好,欢迎注册zblog"
                        + "<h4>" + "您的验证码为" + ":" + content + "</h4>" +
                        "验证码会过期请在120内进行验证哦! "
                        + "</body></html>", true);
            }else {
                helper.setText("<html><body>" +
                        toUser + "您好,您正在修改zblog个人用户信息"
                        + "<h4>" + "您的验证码为" + ":" + content + "</h4>" +
                        "验证码会过期请在120内进行验证哦! "
                        + "</body></html>", true);
            }
            // 标题
            helper.setSubject(subject);
            javaMailSender.send(helper.getMimeMessage());

        } catch (Exception e) {
            throw new UserException(UserStatus.USER_EMAIL_SEND_ERR);
        }

    }


}